from faker import Faker
import random
from datetime import datetime, timedelta
from data_mock.utils import MysqlUtils_AI

fake = Faker('zh_CN')

# ========== 配置 ==========
VISIT_TYPES = ['门诊', '住院', '急诊']
HOSPITALS = [
    {'code': 'HOSP001', 'name': '协和医院'},
    {'code': 'HOSP002', 'name': '华西医院'},
    {'code': 'HOSP003', 'name': '第一人民医院'}
]
PATIENTS = [f"PT{1000+i}" for i in range(100)]
DRUGS = [
    {'generic_name': '阿莫西林', 'trade_name': '阿莫西林胶囊', 'approval_no': 'Z12345678', 'manufac': '北京制药', 'method': '口服'},
    {'generic_name': '头孢克肟', 'trade_name': '头孢克肟胶囊', 'approval_no': 'Z87654321', 'manufac': '上海药业', 'method': '口服'},
]

# ========== 生成函数 ==========
def generate_b02_2_1_records(num_records=50):
    sql_statements = []

    for i in range(num_records):
        hospital = random.choice(HOSPITALS)
        patient_id = random.choice(PATIENTS)
        visit_sn = f"VIS{10000+i}"
        adr_event_sn = f"ADR{10000+i}"
        drug = random.choice(DRUGS)
        start_time = datetime.now() - timedelta(days=random.randint(0, 365))
        end_time = start_time + timedelta(days=random.randint(1,10))
        report_time = end_time + timedelta(days=random.randint(0,5))
        event_time = start_time + timedelta(hours=random.randint(1,48))

        data = {
            'adr_disease_influence': random.choice(['无影响','轻微加重','明显加重']),
            'adr_event_content': fake.text(max_nb_chars=200),
            'adr_event_name': random.choice(['皮疹','恶心','肝功能异常']),
            'adr_event_result': random.choice(['好转','未好转','治愈']),
            'adr_event_sn': adr_event_sn,
            'adr_event_time': event_time.strftime('%Y-%m-%d %H:%M:%S'),
            'adr_family_status': random.choice(['无','有']),
            'adr_original_disease': fake.word(),
            'adr_past_other': fake.text(max_nb_chars=50),
            'adr_past_status': random.choice(['无','有']),
            'adr_report_status': random.choice(['已上报','未上报']),
            'adr_report_time': report_time.strftime('%Y-%m-%d %H:%M:%S'),
            'adr_report_type': random.choice(['初报','复报']),
            'adr_report_unit_appraise': random.choice(['可能相关','可能无关']),
            'adr_reporter_appraise': random.choice(['可能相关','可能无关']),
            'adr_reuse_status': random.choice(['是','否']),
            'adr_stop_status': random.choice(['是','否']),
            'from_table': None,
            'from_yy_record_id': fake.uuid4()[:8],
            'hospital_code': hospital['code'],
            'hospital_name': hospital['name'],
            'hospitalization_times': str(random.randint(1,5)),
            'inpatient_no': f"IP{10000+i}",
            'medical_record_no': f"MR{10000+i}",
            'name': fake.name(),
            'outpatient_no': f"OUT{10000+i}",
            'patient_id': patient_id,
            'patient_id_old': f"PAT_OLD{1000+i}",
            'record_datetime': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'record_status': 1,
            'record_update_datetime': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'suspect_drug_approval_no': drug['approval_no'],
            'suspect_drug_batch_no': f"BATCH{1000+i}",
            'suspect_drug_code': f"DRG{1000+i}",
            'suspect_drug_dosage': f"{random.randint(1,3)}片",
            'suspect_drug_end_time': end_time.strftime('%Y-%m-%d %H:%M:%S'),
            'suspect_drug_generic_name': drug['generic_name'],
            'suspect_drug_manufac': drug['manufac'],
            'suspect_drug_method': drug['method'],
            'suspect_drug_reason': '治疗感染',
            'suspect_drug_start_time': start_time.strftime('%Y-%m-%d %H:%M:%S'),
            'suspect_drug_trade_name': drug['trade_name'],
            'visit_card_no': f"VC{10000+i}",
            'visit_sn': visit_sn,
            'visit_times': str(random.randint(1,5)),
            'visit_type': random.choice(VISIT_TYPES),
            'yy_collection_datetime': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'yy_record_md5': fake.md5(),
            'yy_upload_status': 0,
            'yy_etl_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'yy_batch_time': datetime.now().strftime('%Y%m%d'),
            'yy_record_batch_id': f"BATCH{datetime.now().strftime('%Y%m%d')}_{i}"
        }

        sql_statements.append(generate_sql('b02_2_1', data))

    return sql_statements

# ========== 生成 SQL ==========
def generate_sql(table, data):
    columns = []
    values = []
    for k, v in data.items():
        columns.append(f"`{k}`")
        if v is None:
            values.append("NULL")
        elif isinstance(v, (int, float)):
            values.append(str(v))
        else:
            escaped_value = str(v).replace("'", "''")
            values.append(f"'{escaped_value}'")
    return f"INSERT INTO `{table}` ({', '.join(columns)}) VALUES ({', '.join(values)});"

# ========== 执行生成 ==========
if __name__ == "__main__":
    print("开始生成 b02_2_1 患者药物不良反应数据...")
    records = generate_b02_2_1_records(50)  # 生成50条测试数据
    MysqlUtils_AI.insert_data_to_hub(records, 'b02_2_1')
